import { computed, type Ref } from 'vue'
import type { CodeNullable, CodeRef, TypeNullable, TypeRef } from './types'
import { ClassificationType, type Classification } from '@/models/Classification/Classification'

export interface UseClassificationInfoData {
  type: TypeRef
  code: CodeRef
  list: Ref<Array<Classification>>
}

function getClassificationByTypeAndCode(
  list: Array<Classification>,
  type: TypeNullable,
  code: CodeNullable,
) {
  if (!type || !code) return undefined
  const arr = list
  const loopLen = arr.length
  for (let i = 0; i < loopLen; i++) {
    const item = arr[i]
    if (!item) continue
    if (item.code !== code || item.type !== type) continue
    return item
  }
  return undefined
}

export function useClassificationInfo(data: UseClassificationInfoData) {
  const { type, code, list } = data

  const info = computed(() => getClassificationByTypeAndCode(list.value, type.value, code.value))

  const name = computed(() => (info.value ? info.value.value : ''))

  const secondaryClassification = computed(() => {
    if (type.value === ClassificationType.classification) return undefined
    return info.value
  })
  const classification = computed(() => {
    if (type.value === ClassificationType.classification) return info.value
    if (!info.value) return
    const { parentCode } = info.value
    return getClassificationByTypeAndCode(list.value, ClassificationType.classification, parentCode)
  })

  return { info, name, classification, secondaryClassification }
}
